#include "ClientHandle.h"
#include <QtNetwork>
#include <QMessageBox>

ClientHandle::ClientHandle(QObject *parent) :
	QObject(parent)
{
	_socket = new QTcpSocket(this);

	connect(_socket, SIGNAL(readyRead()), SLOT(onReadReady()));
	connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)),
			this, SLOT(displayError(QAbstractSocket::SocketError)));

	initSession();
}

void ClientHandle::initSession(){
	QNetworkConfigurationManager manager;
	if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
		// Get saved network configuration
		QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
		settings.beginGroup(QLatin1String("QtNetwork"));
		const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
		settings.endGroup();

		// If the saved network configuration is not currently discovered use the system default
		QNetworkConfiguration config = manager.configurationFromIdentifier(id);
		if ((config.state() & QNetworkConfiguration::Discovered) !=
			QNetworkConfiguration::Discovered) {
			config = manager.defaultConfiguration();
		}

		_networkSession = new QNetworkSession(config, this);
		connect(_networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));

		_networkSession->open();
	}
}

void ClientHandle::sessionOpened()
{
	// Save the used configuration
	QNetworkConfiguration config = _networkSession->configuration();
	QString id;
	if (config.type() == QNetworkConfiguration::UserChoice)
		id = _networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
	else
		id = config.identifier();

	QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
	settings.beginGroup(QLatin1String("QtNetwork"));
	settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
	settings.endGroup();
}

void ClientHandle::displayError(QAbstractSocket::SocketError socketError)
{
	switch (socketError) {
	case QAbstractSocket::RemoteHostClosedError:
		break;
	case QAbstractSocket::HostNotFoundError:
		QMessageBox::information(0, tr("Fortune Client"),
								 tr("The host was not found. Please check the "
									"host name and port settings."));
		break;
	case QAbstractSocket::ConnectionRefusedError:
		QMessageBox::information(0, tr("Fortune Client"),
								 tr("The connection was refused by the peer. "
									"Make sure the fortune server is running, "
									"and check that the host name and port "
									"settings are correct."));
		break;
	default:
		QMessageBox::information(0, tr("Fortune Client"),
								 tr("The following error occurred: %1.")
								 .arg(_socket->errorString()));
	}
}

void ClientHandle::setConnection(QString ip, int port){
	_socket->abort();
	_socket->connectToHost(ip,port);
}

void ClientHandle::disconnect(){
	_socket->disconnectFromHost();
	_socket->waitForDisconnected();
}

void ClientHandle::onReadReady(){
	QByteArray data = _socket->readAll();
	emit incomming(data);
}

void ClientHandle::sendData(QByteArray data){
	_socket->write(data);
}
